﻿using log4net;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocketDemo.Manager;
using WebSocketDemo.Models;

namespace WebSocketDemo.Middleware
{
    /// <summary>
    /// 及时通讯WebSocket中间件
    /// </summary>
    public class ChatWebSocketMiddleware
    {
        /// <summary>
        /// .Net Core自带日志对象
        /// </summary>
        private readonly ILogger _logger;

        /// <summary>
        /// Log4net 日志对象
        /// </summary>
        private readonly ILog Log = LogManager.GetLogger(typeof(ChatWebSocketMiddleware));

        /// <summary>
        /// 对用户WebSocket对象进行键值对管理
        /// </summary>
        public static ConcurrentDictionary<string, WebSocket> _sockets = new ConcurrentDictionary<string, WebSocket>();

        /// <summary>
        /// 请求管道
        /// </summary>
        private readonly RequestDelegate _next;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next"></param>
        public ChatWebSocketMiddleware(RequestDelegate next, ILogger<ChatWebSocketMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        /// <summary>
        /// 无参构造函数
        /// </summary>
        public ChatWebSocketMiddleware()
        {

        }

        /// <summary>
        /// 网络请求上下文
        /// </summary>
        public static HttpContext _context;

        /// <summary>
        /// 调用函数
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            _context = context;
            _logger.LogDebug("开始调用...");
            Log.Debug("开始调用...");
            try
            {
                // 不是WebSocket请求直接返回
                if (!context.WebSockets.IsWebSocketRequest)
                {
                    await _next.Invoke(context);
                    return;
                }

                CancellationToken ct = context.RequestAborted;
                var currentSocket = await context.WebSockets.AcceptWebSocketAsync();

                // 获取请求人ID
                string socketId = context.Request.Query["sid"].ToString();

                // 当前WebSocket加入缓存
                if (!_sockets.ContainsKey(socketId))
                {
                    _sockets.TryAdd(socketId, currentSocket);
                }
                else
                {
                    _sockets.Remove(socketId, out WebSocket socket);
                    _sockets.TryAdd(socketId, currentSocket);
                }

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }
                    // 接收文本信息
                    string response = await ReceiveStringAsync(currentSocket, ct);

                    if (string.IsNullOrEmpty(response))
                    {
                        if (currentSocket.State != WebSocketState.Open)
                        {
                            break;
                        }
                        continue;
                    }

                    _logger.LogDebug($"收到文本信息：{response}");
                    Log.Debug($"收到文本信息：{response}");

                    var msg = JsonConvert.DeserializeObject<MsgTemplate>(response);
                    // 发送消息加入缓存
                    MsgHistoryManager.Singleton.AddMsg(msg.SenderID, msg);

                    var msg2 = JsonConvert.DeserializeObject<MsgTemplate>(response);
                    msg2.MessageType = "Receive";
                    // 接收消息加入缓存 不在线也要加入缓存
                    MsgHistoryManager.Singleton.AddMsg(msg.ReceiverID, msg2);


                    foreach (var socket in _sockets)
                    {
                        // 只有接收人才能获取信息
                        if (socket.Key == msg.ReceiverID)
                        {
                            if (socket.Value.State != WebSocketState.Open)
                            {
                                // 未读消息
                                msg2.NotReadMsg = true;
                                Console.OutputEncoding = Encoding.UTF8;
                                _logger.LogDebug($"[WebSocket中间件]Invoke方法已关闭连接");
                                Log.Debug($"[WebSocket中间件]Invoke方法已关闭连接");
                                continue;
                            }

                            await SendStringAsync(socket.Value, JsonConvert.SerializeObject(msg), ct);
                        }
                    }
                }

                // 关闭当前WebSocket
                await currentSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", ct);
                // 释放当前WebSocket
                currentSocket.Dispose();
            }
            catch (Exception ex)
            {
                Console.OutputEncoding = Encoding.UTF8;
                _logger.LogError($"[WebSocket中间件]Invoke方法出错:{ex.Message}");
                Log.Error($"[WebSocket中间件]Invoke方法出错:{ex.Message}");
            }
        }

        /// <summary>
        /// 发送文本信息
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="data"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        public Task SendStringAsync(WebSocket socket, string data, CancellationToken ct = default(CancellationToken))
        {
            _logger.LogDebug($"发送文本信息：{data}");
            Log.Debug($"发送文本信息：{data}");
            try
            {
                var buffer = Encoding.UTF8.GetBytes(data);
                var segment = new ArraySegment<byte>(buffer);
                return socket.SendAsync(segment, WebSocketMessageType.Text, true, ct);
            }
            catch (Exception ex)
            {
                Console.OutputEncoding = Encoding.UTF8;
                _logger.LogError($"[WebSocket中间件]发送文本信息出错:{ex.Message}");
                Log.Error($"[WebSocket中间件]发送文本信息出错:{ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 接收文本信息
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        private async Task<string> ReceiveStringAsync(WebSocket socket, CancellationToken ct = default(CancellationToken))
        {
            try
            {
                var buffer = new ArraySegment<byte>(new byte[8192]);

                using (var ms = new MemoryStream())
                {
                    WebSocketReceiveResult result;
                    do
                    {
                        ct.ThrowIfCancellationRequested();

                        result = await socket.ReceiveAsync(buffer, ct);
                        ms.Write(buffer.Array, buffer.Offset, result.Count);
                    }
                    while (!result.EndOfMessage);

                    ms.Seek(0, SeekOrigin.Begin);

                    if (result.MessageType != WebSocketMessageType.Text)
                    {
                        return null;
                    }

                    using (var reader = new StreamReader(ms, Encoding.UTF8))
                    {
                        return await reader.ReadToEndAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.OutputEncoding = Encoding.UTF8;
                _logger.LogError($"[WebSocket中间件]接收文本信息出错:{ex.Message}");
                Log.Error($"[WebSocket中间件]接收文本信息出错:{ex.Message}");
                return null;
            }
        }
    }
}
